package com.louisgeek.myscanlogin.tool;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by louisgeek on 2018/8/24.
 */
public class ShellTool {
    private static final String TAG = "ShellTool";
    public static final String CMD_SU = "su";
    public static final String CMD_SH = "sh";
    public static final String CMD_EXIT = "exit\n";
    public static final String CMD_LINE_END = "\n";

    /**
     * @return 获取局域网的ip地址形式（32位整型IP地址转成本地ip）
     */
    public static String getLocalIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        // 获取32位整型IP地址
        int ipAddress = wifiInfo.getIpAddress();
        // 返回整型地址转换成“*.*.*.*”地址
        return String.format("%d.%d.%d.%d", (ipAddress & 0xff),
                (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
                (ipAddress >> 24 & 0xff));
    }

    /**
     * 打开adb连接
     *
     * @param tv
     */
    private static boolean isConn;

    public static void openAdb(Context context) {
        if (!isConn) {
            Log.e(TAG, "openAdb: adb connect " + getLocalIpAddress(context));
            execShell("setprop service.adb.tcp.port 5555", RootTool.isRootGranted());
            //  Runtime.getRuntime().exec(new String[]{"/system/bin/su","-c", "setprop service.adb.tcp.port 5555"});
            try {
                Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "start adbd"}); // 
                //  execShell("start adbd");
            } catch (IOException e) {
                e.printStackTrace();
            }
            isConn = true;

        }
    }

    /**
     * 断开adb连接
     */
    public static void closeAdb() {
        try {
            Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "stop adbd"});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重启adb
     */
    public static void restartAdb() {
        try {
            Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "adb kill-server"});
            Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "adb start-server"});
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 安装apk
     */
    public static void installApk(String devName, String apkPath) {
//        String cmd = "pm " + devName + " install -r " + apkPath;
//        String cmd = "pm install -r " + apkPath;
        String cmd = "adb -s " + devName + " install -r " + apkPath;
        execShell(cmd, RootTool.isRootGranted());
    }

    /**
     * 卸载apk
     */
    public static void uninstallApk(Context context, String packageName) {
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "pm uninstall " + packageName});
            if (p == null) {
                Toast.makeText(context, "app 卸载失败", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "app 已成功卸载", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 杀死app
     *
     * @param packageName 包名
     */
    public static void killApp(Context context, String packageName) {
        try {
//            Process p = Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", " am kill  " + packageName});
            Process p = Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", " am force-stop " + packageName});

            if (p == null) {
                Toast.makeText(context, "app 关闭失败", Toast.LENGTH_LONG).show();
            } else {

                Toast.makeText(context, "app  关闭成功", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开app
     *
     * @param packageName
     */
    public static void startApp(Context context, String packageName) {

        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "没有安装", Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 清除apk缓存
     *
     * @param packageName
     */
    public static void clearAppCache(Context context, String packageName) {
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "pm clear " + packageName + " HERE"});
            if (p == null) {
                Toast.makeText(context, "app 缓存数据清空失败", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "app  缓存数据清空成功", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重启手机
     */
    public static void rebootPhone() {
        try {
            Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "reboot"});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭手机
     */
    public static void closePhone() {
        try {
            Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", "reboot -p"});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void execShell(String cmd, boolean isRootGranted) {
        execShell(new String[]{cmd}, isRootGranted);
    }

    public static void execShell(List<String> cmdList, boolean isRootGranted) {
        String[] cmdArr = cmdList.toArray(new String[cmdList.size()]);
        execShell(cmdArr, isRootGranted);
    }

    public static void execShell(String[] cmdArr, boolean isRootGranted) {
        Process process = null;
        DataOutputStream os = null;
        try {
//            process = Runtime.getRuntime().exec(isRootGranted ? CMD_SU : CMD_SH);
            process = Runtime.getRuntime().exec(CMD_SU);
            os = new DataOutputStream(process.getOutputStream());
            for (String cmd : cmdArr) {
                os.write(cmd.getBytes());
                os.writeBytes(CMD_LINE_END);
                os.flush();
            }
            os.writeBytes(CMD_EXIT);
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
    }


}
